<template>
  <view class="address-manage-page">
    <scroll-view class="scroll-content" :scroll-y="true">
      <view v-if="addressList.length > 0" class="address-list">
        <view v-for="address in addressList" :key="address.id" class="address-card">
          <!-- [核心修改] 将“选择”的点击事件绑定在这里 -->
          <view class="address-main" @click="selectAddress(address)">
            <view class="address-icon">{{ address.name.charAt(0) }}</view>
            <view class="address-info">
              <view class="user-info">
                <text>{{ address.name }}</text>
                <text class="phone">{{ address.phone }}</text>
              </view>
              <view class="address-details">{{ address.fullAddress }}</view>
            </view>
          </view>
          <!-- [核心修改] 将按钮区域移到 address-main 的外部，成为其兄弟元素 -->
          <view class="action-buttons">
            <uni-icons type="compose" size="22" color="#888" @click="gotoEditAddress(address.id)"></uni-icons>
            <uni-icons type="trash" size="22" color="#888" @click="deleteAddress(address.id)"></uni-icons>
          </view>
        </view>
      </view>
      <view v-else class="empty-state">
        <image class="empty-image" src="/static/icons/empty-address.svg" mode="widthFix"></image>
        <text class="empty-text">您还没有添加地址</text>
      </view>
    </scroll-view>
    <view class="sticky-footer" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <button class="add-btn" @click="gotoAddAddress">+ 新增服务地址</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useSystemInfo } from '@/composables/useSystemInfo';
import { request } from '@/utils/request.js';
import { getCurrentInstance } from 'vue'; // 引入 getCurrentInstance
// [新增] 导入全局 store
import store from '@/utils/store.js';

const { safeAreaInsets } = useSystemInfo();
const addressList = ref([]);
const instance = getCurrentInstance(); // 获取当前组件实例

// ---- API Methods ----
const fetchAddressList = async () => {
  try {
    const userId = uni.getStorageSync('userId');
    if (!userId) return;
    const data = await request({
      url: '/my/addresses',
      method: 'POST',
      data: { userId: userId }
    });
    const validAddresses = data.filter(addr => addr.addressIsExist !== 0);
    addressList.value = validAddresses.map(addr => ({
      id: addr.addressId,
      name: addr.addressLinkman,
      phone: addr.addressPhone,
      fullAddress: `${addr.addressArea} ${addr.addressDetail}`
    }));
  } catch (error) {
    console.error("获取地址列表失败:", error);
    addressList.value = [];
  }
};

const deleteAddress = (id) => {
  uni.showModal({
    content: '确定要删除这个地址吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await request({
            url: '/my/deleteAddress',
            method: 'POST',
            data: { addressId: id }
          });
          uni.showToast({ title: '删除成功', icon: 'none' });
          fetchAddressList(); 
        } catch (error) {
          console.error("删除地址失败:", error);
        }
      }
    },
  });
};

// [核心修改] selectAddress 方法
const selectAddress = (address) => {
  // 1. 将选中的地址存入全局 store
  store.selectedAddress = address;
  console.log('已将地址存入全局 store:', store.selectedAddress);
  
  // 2. 直接返回上一页
  uni.navigateBack();
};

const gotoAddAddress = () => {
  uni.navigateTo({ url: '/pages/user/address-form' });
};

// [修改] 不再需要 event 参数
const gotoEditAddress = (id) => {
  uni.navigateTo({ url: `/pages/user/address-form?id=${id}` });
};

// --- Lifecycle ---
onShow(() => {
  fetchAddressList();
});
</script>

<style lang="scss" scoped>
/* 样式与之前版本基本一致，但移除了表单相关样式 */
.address-manage-page {
  display: flex; flex-direction: column; height: 100vh; background-color: $uni-bg-color;
}
.scroll-content { flex: 1; height: 0; }
.address-list { padding: 30rpx; }
.address-card {
  position: relative; background-color: $uni-bg-color-white; border-radius: 24rpx;
  padding: 30rpx; margin-bottom: 30rpx; box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
}
.address-main { display: flex; align-items: flex-start; padding-right: 120rpx; }
.address-icon {
  width: 64rpx; height: 64rpx; font-size: 32rpx; font-weight: 500;
  background-color: $uni-primary-light; color: $uni-primary; border-radius: 50%;
  display: flex; justify-content: center; align-items: center; margin-right: 30rpx; flex-shrink: 0;
}
.user-info {
  font-size: 32rpx; font-weight: 500; margin-bottom: 16rpx;
  .phone { margin-left: 20rpx; color: $uni-text-color-light; font-weight: 400; }
}
.address-details { font-size: 28rpx; color: $uni-text-color; line-height: 1.6; }
.action-buttons { position: absolute; top: 30rpx; right: 30rpx; display: flex; gap: 30rpx; }

.sticky-footer {
  position: fixed; bottom: 0; left: 0; right: 0; background: $uni-bg-color-white;
  padding: 24rpx 30rpx; box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.08);
  .add-btn {
    width: 100%; height: 90rpx; line-height: 90rpx;
    background: linear-gradient(135deg, $uni-primary, $uni-accent); color: white;
    border-radius: 45rpx; font-size: 32rpx; font-weight: 500;
  }
}

.empty-state {
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  padding-top: 200rpx;
  .empty-image { width: 200rpx; margin-bottom: 40rpx; }
  .empty-text { font-size: 30rpx; color: $uni-text-color-light; }
}
</style>